import fs from 'file-saver'
import * as XLSX from 'xlsx'

class Tool<T> {
    public len:number | undefined = 0;
    public toolTip:string[] = ["紫外强度","红外的","振动","温度","压力","湿度"]
    public static initNum:number = 0; // 导入excel进度条的进度
    public static total:number = 0;  // 下载的数据量
    constructor(len:number|undefined) {
        // 初始限制数组的长度
        this.len = len
    }

    // 限制数组
     limitArrayLength(arr:Array<T>,num:T):Array<T>  {
      if (typeof num === "number" && !isNaN(num)) {
            if (arr.length >= this.len) {
                arr.shift()
                if (arr.length !== this.len - 1) {
                    this.limitArrayLength(arr,num)
                } else {
                    arr.push(num)
                }
          } else {
            arr.push(num)
          }
      }
      return arr
    }
    // 数据存储
    async saveData(proxy,obj) {
        await proxy.$insideHttp.post("/admin/saveData",obj)
    }
    // 获取数组的平均值
    avgArr(arr:number[]):number {
      let sum:number = arr.reduce((pre,next) => {
          return pre+=next
      },0)
      let avg:number = sum / arr.length
      return Number(avg.toFixed(2))
    }

    // 获取数组里面的最大值
    maxArr(arr:number[]):number {
        return Math.max.apply(null,arr)
    }

    // 获取数组里面的最小值
    minArr(arr:number[]):number {
      return Math.min.apply(null,arr)
    }

    // 获取曲线的最小量程
    getMinValue(arr:number[]):number {
      let min:number = (this.maxArr(arr) - this.minArr(arr) - this.avgArr(arr)) > 0 ? Math.round(this.avgArr(arr) / 2) : 0
      return min
    }

    // 获取曲线的最大量程
    getMaxValue(arr:number[]):number {
      let max:number = Math.round((this.maxArr(arr) - this.minArr(arr) + this.avgArr(arr)) *2)
      console.log(max)
      return max > 0? max : 50
    }

    // 获取需要的字的数组
    getTypeArr(domRef:HTMLElement):string[] {
      let str:string[] = domRef.innerHTML.split("")
      return str
    }

    sumArr(arr:number[]):number {
       let num = arr.reduce((acc,curr) => acc+=curr,0)
       return num
    }

    // 获取当前日期
    getCurrentDate():string {
      let date:Date = new Date()
      let str:string = date.toLocaleDateString().replace(/\//g,"-")
      return str
    }          
    xlsx(json, fields, filename = '.xlsx') {//导出xlsx
      json.forEach(item => {
        for (let i in item) {
          if (fields.hasOwnProperty(i)) {
            item[fields[i]] = item[i];
          }
          delete item[i]; //删除原先的对象属性
        }
      })
      let sheetName = filename //excel的文件名称
      let wb = XLSX.utils.book_new()  //工作簿对象包含一SheetNames数组，以及一个表对象映射表名称到表对象。XLSX.utils.book_new实用函数创建一个新的工作簿对象。
      let ws = XLSX.utils.json_to_sheet(json, { header: Object.values(fields) }) //将JS对象数组转换为工作表。
      wb.SheetNames.push(sheetName)
      wb.Sheets[sheetName] = ws
      const defaultCellStyle = { font: { name: "Verdana", sz: 13, color: "FF00FF88" }, fill: { fgColor: { rgb: "FFFFAA00" } } };//设置表格的样式
      let wopts = { bookType: 'xlsx', bookSST: false, type: 'binary', cellStyles: true, defaultCellStyle: defaultCellStyle, showGridLines: false }  //写入的样式
      let wbout = XLSX.write(wb, wopts)
      let blob = new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' })
      fs.saveAs(blob, filename + '.xlsx')
    }
    s2ab(s) {
      var buf;
      if (typeof ArrayBuffer !== 'undefined') {
        buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff
        return buf
      } else {
        buf = new Array(s.length);
        for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
    }

    // 修改设备的状态
    async changeState(proxy,obj) {
      await proxy.$insideHttp.post("/updateState",obj)
    }

    // 获取时间的字符串
    getTimeStr(currentTime:any) {
      let date = new Date(currentTime)
      let year = date.getFullYear()
      let month:any = date.getMonth() + 1
      month = month >= 10? month: '0' + month
      let day:any = date.getDate()
      day = day >= 10? day: '0' + day
      let hour = date.getHours() >= 10? date.getHours(): '0'+ date.getHours() // 获取小时
      let min = date.getMinutes()>= 10? date.getMinutes(): '0' + date.getMinutes() // 获取分钟
      let second = date.getSeconds() >= 10? date.getSeconds(): '0' + date.getSeconds() // 获取秒数
      return year + '-' + month + '-' + day + ' ' + hour + ':' +  min + ':' + second
    }
       // 关闭放大初始化数组
       initArrayLength(arr:Array<T>):Array<T> {
        if (arr.length <= this.len) return arr
        return arr.slice(arr.length - this.len,arr.length + 1)
        }

    // 通用日期格式化方法
    formatDate(date: Date | number | string, fmt: string = 'YYYY-MM-DD hh:mm:ss'): string {
        let d = date instanceof Date ? date : new Date(date);
        const o: Record<string, number> = {
            'M+': d.getMonth() + 1,
            'D+': d.getDate(),
            'h+': d.getHours(),
            'm+': d.getMinutes(),
            's+': d.getSeconds(),
        };
        if (/(Y+)/.test(fmt)) {
            fmt = fmt.replace(RegExp.$1, d.getFullYear().toString().slice(4 - RegExp.$1.length));
        }
        for (let k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, o[k].toString().padStart(RegExp.$1.length, '0'));
            }
        }
        return fmt;
    }
}    
// 定义一个全局的工具对象
let tool = new Tool<number>(10)

// 定义全屏和缩小全屏的函数
const launchFullscreen = (element: any) => {
  if(element.requestFullscreen) {
   element.requestFullscreen();
  } else if(element.mozRequestFullScreen) {
   element.mozRequestFullScreen();
  } else if(element.webkitRequestFullscreen) {
   element.webkitRequestFullscreen();
  } else if(element.msRequestFullscreen) {
   element.msRequestFullscreen();
  }
 }
 
 const exitFullscreen = () => {
  if(document.exitFullscreen) {
   document.exitFullscreen();
  } else if(document.mozCancelFullScreen) {
   document.mozCancelFullScreen();
  } else if(document.webkitExitFullscreen) {
   document.webkitExitFullscreen();
  }
 }

// 导出实列的对象和类 
export default {
  tool,
  Tool,
  launchFullscreen,
  exitFullscreen
}
